<template>
  <div class="root">
    <m-header hasIconBorder title="识别人脸">
      <div slot="left" v-on:click="exitProgram"><img class="m-icon-img margin-right-10" src="../assets/images/menu_close.png" /></div>
      <div slot="right"><img class="m-icon-img margin-right-10" src="../assets/images/menu_more.png" /></div>
    </m-header>

    <label for="filechooser" class="content selfie-main" id="selfie-main">
       <input id="filechooser" type="file" accept="image/*;" capture="camera" style="display:none;" />
    </label>
  </div>
</template>

<script>
  import mHeader from '../components/header'
  import util from '../util/util.js'
  import EXIF from 'exif-js'
  export default {
    components: {
      mHeader,
    },
    data() {
      return {

      }
    },
    methods: {

      bindUploadImgEvent() {
        let _this = this;
        let filechooser = document.getElementById('filechooser');
        filechooser.onchange = function () {
          let file = this.files[0];

          // 图片方向角
          var Orientation = null;

          if (file) {
            // 接受 jpeg, jpg, png 类型的图片
            if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) {
              return util.toast('不支持的文件格式');
            }
            //获取照片方向角属性
            EXIF.getData(file, function () {
              EXIF.getAllTags(this);
              Orientation = EXIF.getTag(this, 'Orientation');
              console.log('1. orientation = ' + Orientation + ' , date = ' + new Date());
            });
          }
          var reader = new FileReader();
          _this.$store.dispatch('showLoading');
          // console.log('3. readAsDataURL' + ' , date = ' + new Date());
          reader.readAsDataURL(file);
          reader.onload = function (e) {
            var image = new Image();
            // console.log('4. image start load' + ' , date = ' + new Date());
            image.src = e.target.result;
            image.onload = function () {
              // console.log('5. image over load' + ' , date = ' + new Date());
              var canvas = document.createElement("canvas");
              var ctx = canvas.getContext("2d");

              const maxH = 800;
              if (image.height > maxH) {
                image.width *= maxH / image.height;
                image.height = maxH;
              }
              canvas.width = image.width;
              canvas.height = image.height;
              ctx.drawImage(image, 0, 0, image.width, image.height);

              var base64 = null;
              console.log('2. orientation = ' + Orientation);
              if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                var width = this.naturalWidth;
                var height = this.naturalHeight;
                switch (Orientation) {
                  case 6: //需要顺时针90度旋转
                    // canvas.width = height;
                    // canvas.height = width;

                    canvas.width = image.height;
                    canvas.height = image.width;
                    ctx.rotate(90 * Math.PI / 180);
                    ctx.drawImage(this, 0, -height);
                    break;
                  case 8: //需要逆时针90度旋转
                    // canvas.width = height;
                    // canvas.height = width;

                    canvas.width = image.height;
                    canvas.height = image.width;
                    ctx.rotate(-90 * Math.PI / 180);
                    ctx.drawImage(this, -width, 0);
                    break;
                  case 3: //需要180度旋转
                    ctx.rotate(180 * Math.PI / 180);
                    ctx.drawImage(this, -width, -height);
                    break;
                }
              }
              // console.log('6. canvas.toDataURL start ' + ' , date = ' + new Date());
              base64 = canvas.toDataURL('image/jpeg', 0.92);
              // console.log('7. canvas.toDataURL over ' + ' , date = ' + new Date());

              _this.setImg(base64);
              _this.uploadImg(base64);
            };
          };
        };
      },

      setImg(dataUrl) {
        let bg = document.getElementById('selfie-main');
        bg.style.backgroundImage = "url(" + dataUrl + ")";
      },

      uploadImg(dataUrl) {
        let _this = this;

        const blob = this.dataURLtoBlob(dataUrl);
        const formData = new FormData();
        formData.append('file', blob);

        let xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
          console.log('readyState = ' + xhr.readyState);
          //服务器连接已建立
          if (xhr.readyState === 1) {
            _this.$store.dispatch('showLoading');
          }
          //请求已完成，且响应已就绪
          if (xhr.readyState === 4) {
            _this.$store.dispatch('hideLoading');
            if (xhr.status === 200) {
              // 上传成功，获取到结果 results
              console.log(xhr.responseText);
              let response = JSON.parse(xhr.responseText);

              if (response.code === '0') {
                _this.$store.dispatch('setHasAuth', '1');
                _this.$router.replace('/inputsecretsignal');
              } else {
                util.toast(response.msg);
              }

            } else {
              // 上传失败
              util.toast('网络异常');
            }
          }
        };
        // let url = 'http://120.24.89.166:520/ar-social/api/user/recognize/self';
        let url = util.getHost() + '/ar-social/api/user/recognize/self';
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Authorization', this.$store.state.token);
        xhr.send(formData);
      },

      dataURLtoBlob(dataURL) {
        console.log('dataURLtoBlob');
        let binaryString = atob(dataURL.split(',')[1]);
        let arrayBuffer = new ArrayBuffer(binaryString.length);
        let intArray = new Uint8Array(arrayBuffer);
        let mime = dataURL.split(',')[0].match(/:(.*?);/)[1]

        for (let i = 0, j = binaryString.length; i < j; i++) {
          intArray[i] = binaryString.charCodeAt(i);
        }

        let data = [intArray];
        let result = new Blob(data, {
          type: mime
        });
        console.log(result);
        return result;
      },

      setPhotoType() {
        console.log('setPhotoType type=2');
        var url = 'jsbridge://setSelectType?type=2';
        var iframe = document.createElement('iframe');
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        console.log('setPhotoType over');
        setTimeout(function () {
          iframe.remove();
        }, 100);
      },

      exitProgram() {
        console.log('exitProgram');
        var url = 'jsbridge://exitProgram';
        var iframe = document.createElement('iframe');
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        setTimeout(function () {
          iframe.remove();
        }, 100);
      }
    },
    mounted() {
      this.setPhotoType();
      this.bindUploadImgEvent();
    }
  }

</script>

<style lang="less" scoped>
  .selfie-main {
    background-image: url(../assets/images/default_selfie_bg.png);
    /*background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490538835&di=6a151de7508d0006c0bbbdf37844ce3f&imgtype=jpg&er=1&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8601a18b87d6277f01ef72382a381f30e924fc35.jpg);*/
    /* 背景图垂直、水平均居中 */
    background-position: center center;
    /* 背景图不平铺 */
    background-repeat: no-repeat;
    /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
    background-attachment: fixed;
    /* 让背景图基于容器大小伸缩 */
    background-size: cover;
    /* 设置背景颜色，背景图加载过程中会显示背景色 */
    background-color: #464646;
  }

</style>
